﻿
namespace SistemaLogistica.Windows.Forms.Transporte.Operaciones
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;
    using EDOSwit.Controls.DataGridView;
    using EDOSwit.Controls.EventArgs;
    using EDOSwit.Controls.Helpers;
    using EDOSwit.Controls.Types;
    using EDOSwit.Controls.UserControls;
    using SistemaLogistica.Business.Entities;
    using SistemaLogistica.Business.Logic;
    using SistemaLogistica.Windows.Helpers;

    public partial class CwfAlquilerVehiculo : MaestroDetalleSeguro, Observador
    {
        public CwfAlquilerVehiculo()
        {
            InitializeComponent();

            this.dgvVehiculos.DataGridView.KeyDown += new KeyEventHandler(DataGridView_KeyDown);
        }

        protected override void LoadPermisos()
        {
            this.TsMenu.Permisos.AddRange(Metodos.GetPermisos(Convert.ToByte(this.Tag)));
        }

        protected override void FocusKeyPress(object sender, KeyPressEventArgs e)
        {
            base.FocusKeyPress(sender, e);
        }

        protected override void InitialLoad()
        {
            try
            {
                LoadProveedores();
                this.MaestroBindingSource.DataSource = AlquilerVehiculoManager.Instancia.Listar();
                this.dgvMaestro.DataSource = this.MaestroBindingSource;
                OcultarColumnas();
                LoadDataGridView();
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
        }

        private void LoadProveedores()
        {
            this.cmbProveedor.DisplayMember = "RazonSocial";
            this.cmbProveedor.ValueMember = "IdProveedor";
            this.cmbProveedor.DisplayColumnNames = "IdProveedor, Ruc, RazonSocial, Direccion, Telefono";
            this.cmbProveedor.DataSource = ProveedorManager.Instancia.Listar();
        }

        private void OcultarColumnas()
        {
            this.dgvMaestro.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.dgvMaestro.Columns["Comentarios"].Visible = false;
            this.dgvMaestro.Columns["Cantidad"].Visible = false;
            this.dgvMaestro.Columns["Proveedor"].Visible = false;
            this.dgvMaestro.Columns["VehiculoAlquilado"].HeaderText = "Alquileres";
            this.dgvMaestro.Columns["VehiculoAlquilado"].DisplayIndex = 0;
        }

        private void LoadDataGridView()
        {
            this.dgvVehiculos.DataGridView.Rows.Clear();
            this.dgvVehiculos.DataGridView.Columns.Clear();
            this.dgvVehiculos.Mode = Mode.ReadOnly;

            CustomColumnDataGridView colummn = new CustomColumnDataGridView();
            colummn.Name = "Vehiculo";
            colummn.HeaderText = "Vehiculo";
            colummn.Width = 150;
            colummn.ControlType = CustomControlType.FindDropDownList;
            this.dgvVehiculos.CustomColumns.AddColumn(colummn);

            colummn = new CustomColumnDataGridView();
            colummn.Name = "Especificacion";
            colummn.HeaderText = "Especificación";
            colummn.ControlType = CustomControlType.TextBox;
            this.dgvVehiculos.CustomColumns.AddColumn(colummn);

            this.dgvVehiculos.DataGridView.Rows.Add();
            this.dgvVehiculos.DataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        protected override void CellPainting(ref DataGridViewCellPaintingEventArgs e)
        {
            Graphics g = e.Graphics;
            bool selected = ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected);
            Color fcolor = (selected ? e.CellStyle.SelectionForeColor : e.CellStyle.ForeColor);
            Color bcolor = (selected ? e.CellStyle.SelectionBackColor : e.CellStyle.BackColor);
            Font font = e.CellStyle.Font;
            font = new Font("Tahoma", 7);

            AlquilerVehiculo alquiler = this.MaestroBindingSource[e.RowIndex] as AlquilerVehiculo;

            if (alquiler != null)
            {
                int x = e.CellBounds.Left + e.CellStyle.Padding.Left;
                int y = e.CellBounds.Top + e.CellStyle.Padding.Top;
                int width = e.CellBounds.Width - (e.CellStyle.Padding.Left + e.CellStyle.Padding.Right);
                int height = 13 + (e.CellStyle.Padding.Top + e.CellStyle.Padding.Bottom);

                g.FillRectangle(new SolidBrush(bcolor), e.CellBounds);

                y = y + height - 1;

                if (e.ColumnIndex == 0)
                {
                    font = new Font("Tahoma", 9, FontStyle.Bold);
                    if (selected)
                        TextRenderer.DrawText(e.Graphics, alquiler.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, alquiler.Fecha.ToShortDateString(), font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
                else
                {
                    font = new Font("Tahoma", 8, FontStyle.Bold);

                    if (selected)
                        TextRenderer.DrawText(e.Graphics, alquiler.Proveedor.RazonSocial, font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                    else
                        TextRenderer.DrawText(e.Graphics, alquiler.Proveedor.RazonSocial, font, new Rectangle(x, y, width, height), System.Drawing.Color.Blue, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);

                    font = new Font("Tahoma", 8);
                    y = y + height - 1;
                    TextRenderer.DrawText(e.Graphics, "RUCº: " + alquiler.Proveedor.Ruc, font, new Rectangle(x, y, width, height), fcolor, TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.EndEllipsis);
                }
            }
        }

        protected override void EventoNuevo()
        {
            this.dtpFecha.Enabled = false;
            this.dtpFecha.Value = EmpresaManager.Instancia.Fecha();
            this.dtpFecha.Focus();
        }

        protected override void EventoEditar()
        {
            this.dtpFecha.Enabled = true;
            this.dtpFecha.Focus();
        }

        protected override void EventoGuardar()
        {
            this.dgvVehiculos.Mode = Mode.ReadOnly;
        }

        protected override void EventoCancelar()
        {
            this.dgvVehiculos.Mode = Mode.ReadOnly;
        }

        private void dgvVehiculos_BeforeShowControl(object sender, BeforeShowControlEventArg e)
        {
            switch (e.Cell.ColumnIndex)
            {
                case 0: // Cargar Vehiculos
                    try
                    {
                        List<VehiculoAlquilado> vehiculos = VehiculoManager.Instancia.ListarAlquilados();
                        ComboBox cmbA = e.Control as ComboBox;
                        cmbA.DataSource = null;
                        cmbA.DisplayMember = "Vehiculo";
                        cmbA.ValueMember = "IdBien";
                        cmbA.DataSource = vehiculos;
                    }
                    catch (Exception ex)
                    {
                        Mensaje.ShowMessageAlert(this.ParentForm, Constantes.TituloMensaje, ex.Message);
                    }
                    break;
                default:
                    break;
            }
        }

        private void dgvVehiculos_EnterKeyPress(object sender, EnterKeyPressEventArg e)
        {
            switch (e.ColumnIndex)
            {
                case 0: // Vehiculo
                    if (!string.IsNullOrEmpty(e.Text))
                    {
                        foreach (DataGridViewRow row in this.dgvVehiculos.DataGridView.Rows)
                        {
                            if (row.Index != e.RowIndex)
                            {
                                if (row.Cells[0].Value.ToString() == e.Text)
                                {
                                    e.Handle = false;
                                    Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, "Vehiculo Seleccionado anteriormente");
                                    return;
                                }
                            }
                        }
                        VehiculoAlquilado vehiculo = VehiculoManager.Instancia.BuscarAlquiladoFull(e.Text);
                        if (vehiculo != null)
                        {
                            this.dgvVehiculos.DataGridView.Rows[e.RowIndex].Cells[1].Value = "Vehiculo Alquilado por S/." + vehiculo.Precio;
                            this.dgvVehiculos.DataGridView.Rows[e.RowIndex].Cells[1].Tag = vehiculo.IdVehiculoAlquilado;
                        }
                        else
                        {
                            e.Handle = false;
                        }
                    }
                    else
                    {
                        e.Handle = false;
                    }
                    break;
                case 1: // Descripcion
                    if (string.IsNullOrEmpty(e.Text))
                    {
                        e.Handle = false;
                    }
                    else
                    {
                        if (this.dgvVehiculos.DataGridView.Rows[e.RowIndex].Cells[0].Tag != null)
                        {
                            int count = this.dgvVehiculos.DataGridView.Rows.Count;
                            if (this.dgvVehiculos.DataGridView.Rows[count - 1].Cells[1].Value != null)
                            {
                                this.dgvVehiculos.DataGridView.Rows.Add();
                            }
                        }
                        else
                        {
                            e.Handle = false;
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        private void DataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (this.dgvVehiculos.DataGridView.CurrentCell != null)
                {
                    if (Mensaje.ShowMessageConfirm(this.ParentForm, Constantes.TituloMensaje, "¿Desea eliminar el Detalle?") == DialogResult.No)
                    {
                        e.Handled = true;
                    }
                    else
                    {
                        this.dgvVehiculos.DataGridView.Rows.Remove(this.dgvVehiculos.DataGridView.CurrentRow);
                        if (this.dgvVehiculos.DataGridView.Rows.Count == 0)
                        {
                            this.dgvVehiculos.DataGridView.Rows.Add();
                        }
                    }
                }
            }
        }

        protected override void LoadData(object obj)
        {
            AlquilerVehiculo alquiler = obj as AlquilerVehiculo;
            if (alquiler != null)
            {
                this.identificador = alquiler.Proveedor.IdProveedor;
                this.dtpFecha.Value = alquiler.Fecha;

                List<AlquilerVehiculo> alquileres = AlquilerVehiculoManager.Instancia.ListarPorFecha(alquiler.Proveedor.IdProveedor, alquiler.Fecha);

                int index = 0;
                this.dgvVehiculos.DataGridView.Rows.Clear();
                foreach (AlquilerVehiculo d in alquileres)
                {
                    index = this.dgvVehiculos.DataGridView.Rows.Add(1);
                    this.dgvVehiculos.DataGridView.Rows[index].Cells[0].Value = d.VehiculoAlquilado.ToString();
                    this.dgvVehiculos.DataGridView.Rows[index].Cells[0].Tag = d.VehiculoAlquilado.IdBien;
                    this.dgvVehiculos.DataGridView.Rows[index].Cells[1].Value = d.Comentarios;
                    this.dgvVehiculos.DataGridView.Rows[index].Cells[1].Tag = d.VehiculoAlquilado.IdVehiculoAlquilado;
                }
                this.dgvVehiculos.DataGridView.Rows.Add();
            }
        }

        protected override bool SaveData()
        {
            bool result = false;
            int posicion = this.MaestroBindingSource.Position;

            try
            {
                switch (this.estadoActual)
                {
                    case EstadoActual.Nuevo:
                        AlquilerVehiculoManager.Instancia.Registrar(GetAlquiler());
                        break;
                    case EstadoActual.Editar:
                        AlquilerVehiculoManager.Instancia.Modificar(GetAlquiler());
                        break;
                    case EstadoActual.Eliminar:
                        AlquilerVehiculoManager.Instancia.Eliminar(Convert.ToInt32(this.cmbProveedor.SelectedValue), this.dtpFecha.Value);
                        this.MaestroBindingSource.RemoveCurrent();
                        posicion -= 1;
                        break;
                }
                result = true;
                InitialLoad();
                this.MaestroBindingSource.Position = posicion;
            }
            catch (Exception ex)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, ex.Message);
            }
            return result;
        }

        private List<AlquilerVehiculo> GetAlquiler()
        {
            List<AlquilerVehiculo> alquiler = new List<AlquilerVehiculo>();
            foreach (DataGridViewRow row in this.dgvVehiculos.DataGridView.Rows)
            {
                if (ValidateData(row.Index))
                {
                    alquiler.Add(new AlquilerVehiculo
                    {
                        Proveedor = new Proveedor { IdProveedor = Convert.ToInt32(this.cmbProveedor.SelectedValue) },
                        VehiculoAlquilado = new VehiculoAlquilado
                        {
                            IdBien = Convert.ToInt32(row.Cells[0].Tag),
                            IdVehiculoAlquilado = Convert.ToInt32(row.Cells[1].Tag)
                        },
                        Comentarios = row.Cells[1].Value.ToString(),
                        Cantidad = 1,
                        Fecha = this.dtpFecha.Value
                    });
                }
            }
            return alquiler;
        }

        private bool ValidateData(int rowIndex)
        {
            bool result = true;

            if (this.dgvVehiculos.DataGridView.Rows[rowIndex].Cells[0].Tag == null)
            {
                result = false;
            }
            if (this.dgvVehiculos.DataGridView.Rows[rowIndex].Cells[1].Value == null)
            {
                result = false;
            }
            return result;
        }

        protected override bool ValidateData()
        {
            bool result = true;

            if (this.cmbProveedor.SelectedIndex == -1)
            {
                this.errValidator.SetError(this.cmbProveedor, "Seleccionar Proveedor.");
                result = false;
            }
            else
            {
                this.errValidator.SetError(this.cmbProveedor, string.Empty);
            }
            if (this.dgvVehiculos.DataGridView.Rows.Count == 0)
            {
                Mensaje.ShowMessageAlert(this.ParentForm, this.Titulo, "Debe Agregar los Vehiculos Alquilados.");
                result = false;
            }
            return result;
        }

        protected override void ClearControls()
        {
            this.identificador = 0;
            LoadDataGridView();
            base.ClearControls();
        }

        #region Miembros de Observador

        public void Notificar(object mensaje)
        {
            LoadProveedores();
        }

        #endregion
    }
}
